package com.magicsoft.app.helper;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.provider.ContactsContract.DataUsageFeedback;
import android.util.Log;

import com.loopj.android.http.RequestParams;
import com.magicsoft.app.entity.RememberEntity;
import com.ttcaca.cas.android.client.model.User;
import com.ttcaca.cas.android.client.utils.Encoder;

public class TokenHelper {

	// public static String appID = "ICEXCGJ0-5F89-4E17-BC44-7A0DB101B245";
	// public static String token = "AXPHrD48LRa8xYVkgV4c";
	public static String appID = "ICEHJY00-3A88-4E17-BC84-5A2DB101B226";
	public static String token = "BXPHrDC8ARa8xYVkgV5c";

	// public static boolean encrypt = false;
	
	/**
	 * Case 添加关注人
	 * 
	 * @param context
	 *            上下文
	 * @param isCarryToken
	 *            是否需要携带token,true为携带，false为不携带
	 * @return
	 * @throws UnsupportedEncodingException
	 */
		public static RequestParams FetchAddCaseMembers(Context context,
				boolean isCarryNameAndPassword, String corp_id, String case_id,
				String members, String operator_id, String operator)
				throws UnsupportedEncodingException {
			RequestParams param = new RequestParams();
			long ts = DateUtils.getCurrentDate();

			String sign;
			try {
				sign = getToken(ts + "");
				if (isCarryNameAndPassword) {
					param.put("sign", sign);
					param.put("ts", ts + "");
					param.put("appID", appID);
					param.put("corp_id", corp_id);
					param.put("case_id", case_id);
					param.put("members", members);
					param.put("operator_id", operator_id);
					param.put("operator", operator);
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}

			return param;
		}
	/**
	 * Case 附件上传
	 * 
	 * @param context
	 *            上下文
	 * @param isCarryToken
	 *            是否需要携带token,true为携带，false为不携带
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	// 上传附件
	public static RequestParams FetchUpLoadCaseFiles(Context context,
			boolean isCarryNameAndPassword, String corp_id, String case_id,
			String file_name, String operator_id, String operator)
			throws UnsupportedEncodingException {
		RequestParams param = new RequestParams();
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			if (isCarryNameAndPassword) {
				param.put("sign", sign);
				param.put("ts", ts + "");
				param.put("appID", appID);
				param.put("corp_id", corp_id);
				param.put("case_id", case_id);
				param.put("file_name", file_name);
				param.put("operator_id", operator_id);
				param.put("operator", operator);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return param;
	}

	/**
	 * 添加Case
	 * 
	 * @param context
	 *            上下文
	 * @param isCarryToken
	 *            是否需要携带token,true为携带，false为不携带
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static RequestParams FetchAddCase(Context context,
			boolean isCarryNameAndPassword, String title, String desc, String priority, String operator_id, String operator)
			throws UnsupportedEncodingException {
		RequestParams param = new RequestParams();
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			if (isCarryNameAndPassword) {
				param.put("sign", sign);
				param.put("ts", ts + "");
				param.put("appID", appID);
				param.put("title", title);
				param.put("desc", desc);
				param.put("priority", priority);
				param.put("operator_id", operator_id);
				param.put("operator", operator);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return param;
	}

	/**
	 * 添加Trends
	 * 
	 * @param context
	 *            上下文
	 * @param isCarryToken
	 *            是否需要携带token,true为携带，false为不携带
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static RequestParams FetchAddTrends(Context context,
			boolean isCarryNameAndPassword, String corp_id, String case_id,
			String content, String operator_id, String operator)
			throws UnsupportedEncodingException {
		RequestParams param = new RequestParams();
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			if (isCarryNameAndPassword) {
				param.put("sign", sign);
				param.put("ts", ts + "");
				param.put("appID", appID);
				param.put("corp_id", corp_id);
				param.put("case_id", case_id);
				param.put("content", content);
				param.put("operator_id", operator_id);
				param.put("operator", operator);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return param;
	}

	/**
	 * 获取WeiTown的Token
	 * 
	 * @param context
	 *            上下文
	 * @param isCarryToken
	 *            是否需要携带token,true为携带，false为不携带
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static RequestParams FetchChangeCaseDetail(Context context,
			boolean isCarryNameAndPassword, String corp_id, String cid,
			String title, String desc,
			String type_id, String priority, String status, String operator_id,
			String operator) throws UnsupportedEncodingException {
		RequestParams param = new RequestParams();
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			if (isCarryNameAndPassword) {
				param.put("sign", sign);
				param.put("ts", ts + "");
				param.put("appID", appID);
				param.put("corp_id", corp_id);
				param.put("cid", cid);
				param.put("title", title);
				param.put("desc", desc);
				param.put("type_id", type_id);
				param.put("priority", priority);
				param.put("status", status);
				param.put("operator_id", operator_id);
				param.put("operator", operator);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return param;
	}

	/**
	 * 获取WeiTown的Token
	 * 
	 * @param context
	 *            上下文
	 * @param isCarryToken
	 *            是否需要携带token,true为携带，false为不携带
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	// 新建群组
	public static RequestParams FetchColourToken5(Context context,
			boolean isCarryNameAndPassword, String owner, String groupname,
			String desc, boolean approval, String maxusers, String members)
			throws UnsupportedEncodingException {
		RequestParams param = new RequestParams();
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			if (isCarryNameAndPassword) {
				param.put("sign", sign);
				param.put("ts", ts + "");
				param.put("appID", appID);
				param.put("public", true);
				param.put("owner", owner);
				param.put("groupname", groupname);
				param.put("desc", desc);
				param.put("approval", approval);
				param.put("maxusers", maxusers);
				param.put("members", members);
//				param.put("caseID", caseID);
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return param;
	}

	// 注册用户
	public static RequestParams FetchColourToken6(Context context,
			boolean isCarryNameAndPassword, String account, String password,
			String mobile, String mail) throws UnsupportedEncodingException {
		RequestParams param = new RequestParams();
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			if (isCarryNameAndPassword) {
				param.put("sign", sign);
				param.put("ts", ts + "");
				param.put("appID", appID);
				param.put("account", account);
				param.put("password", password);
				param.put("mobile", mobile);
				param.put("mail", mail);
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return param;
	}

	public static String FetchColourToken(Context context,
			boolean isCarryNameAndPassword) throws UnsupportedEncodingException {

		// Date d = new Date();
		// SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		// String timestamp = formatter.format(d);
		long ts = DateUtils.getCurrentDate();

		String params = "";
		try {

			if (isCarryNameAndPassword) {

				RememberEntity rememberEntity = SharePreferenceHelper
						.GetRememberEntity(context);
				String username = rememberEntity.getAdmin();
				String password = rememberEntity.getPsw();
				params =
				// "?encrypt=" + encrypt +
				"?appID=" + appID + "&ts=" + ts + "&sign=" + getToken(ts + "")
						+ "&loginUsername=" + username + "&loginPassword="
						+ password;
			} else {
				params =
				// "?encrypt=" + encrypt +
				"?appID=" + appID + "&ts=" + ts + "&sign=" + getToken(ts + "");
			}

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return params;
	}

	public static RequestParams FetchColourToken1(Context context,
			boolean isCarryNameAndPassword, String username, String password)
			throws UnsupportedEncodingException {
		RequestParams param = new RequestParams();
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			if (isCarryNameAndPassword) {
				param.put("sign", sign);
				param.put("ts", ts + "");
				param.put("appID", appID);
				param.put("username", username);
				param.put("password", password);
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return param;
	}

	public static RequestParams FetchColourToken3(Context context,
			boolean isCarryNameAndPassword, String id, String mobile,
			String mail, String realname, String sex, String fixed_line,
			String id_card_no, String address, String education)
			throws UnsupportedEncodingException {
		RequestParams param = new RequestParams();
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			if (isCarryNameAndPassword) {
				param.put("sign", sign);
				param.put("ts", ts + "");
				param.put("appID", appID);
				param.put("id", id);
				param.put("mobile", mobile);
				param.put("mail", mail);
				param.put("realname", realname);
				param.put("sex", sex);
				param.put("fixed_line", fixed_line);
				param.put("id_card_no", id_card_no);
				param.put("address", address);
				param.put("education", education);
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return param;
	}

	public static RequestParams FetchColourToken4(Context context,
			boolean isCarryNameAndPassword, String username,
			String oldpassword, String newpassword)
			throws UnsupportedEncodingException {
		RequestParams param = new RequestParams();
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			if (isCarryNameAndPassword) {
				param.put("sign", sign);
				param.put("ts", ts + "");
				param.put("appID", appID);
				param.put("username", username);
				param.put("oldpassword", oldpassword);
				param.put("newpassword", newpassword);
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return param;
	}

	public static String FetchColourToken2(Context context, String accountid,
			boolean isCarryNameAndPassword) throws UnsupportedEncodingException {

		long ts = DateUtils.getCurrentDate();
		String params = "";
		try {

			if (isCarryNameAndPassword) {
				params = "?accountid=" + accountid + "&appID=" + appID + "&ts="
						+ ts + "&sign=" + getToken(ts + "");
			} else {
				params =
				// "?encrypt=" + encrypt +
				"?appID=" + appID + "&ts=" + ts + "&sign=" + getToken(ts + "");
			}

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return params;
	}

	// 摇一摇
	public static String FetchColourToken_yaoyiyao(Context context,
			boolean isCarryNameAndPassword) throws UnsupportedEncodingException {

		long ts = DateUtils.getCurrentDate();
		String params = "";
		try {

			if (isCarryNameAndPassword) {
				params = "?appID=" + appID + "&ts=" + ts + "&sign="
						+ getToken(ts + "");
			} else {
				params =
				// "?encrypt=" + encrypt +
				"?appID=" + appID + "&ts=" + ts + "&sign=" + getToken(ts + "");
			}

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return params;
	}

	// 搜一搜
	public static String FetchColourToken_souyisou(Context context,
			boolean isCarryNameAndPassword, int pageID, int pageSize)
			throws UnsupportedEncodingException {

		long ts = DateUtils.getCurrentDate();
		String params = "";
		try {

			if (isCarryNameAndPassword) {
				params = "?pageID=" + pageID + "pageSize=" + pageSize
						+ "&appID=" + appID + "&ts=" + ts + "&sign="
						+ getToken(ts + "");
			} else {
				params = "?pageID=" + pageID + "pageSize=" + pageSize
						+ "&appID=" + appID + "&ts=" + ts + "&sign="
						+ getToken(ts + "");
			}

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return params;
	}

	// 获取用户信息
	public static String FetchColourToken_getuserid(Context context,
			boolean isCarryNameAndPassword, String username)
			throws UnsupportedEncodingException {

		long ts = DateUtils.getCurrentDate();
		String params = "";
		try {

			if (isCarryNameAndPassword) {
				params = "username=" + username + "&appID=" + appID + "&ts="
						+ ts + "&sign=" + getToken(ts + "");
			} else {
				params = "&appID=" + appID + "&ts=" + ts + "&sign="
						+ getToken(ts + "");
			}

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return params;
	}

	/**
	 * 获取WeiTown的Token
	 * 
	 * @param context
	 *            上下文
	 * @param isCarryToken
	 *            是否需要携带token,true为携带，false为不携带
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String FetchToken2(Context context)
			throws UnsupportedEncodingException {

		// Date d = new Date();
		// SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		// String timestamp = formatter.format(d);
		long ts = DateUtils.getCurrentDate();

		String params = "";
		try {
			params =
			// "?encrypt=" + encrypt +
			"&appID=" + appID + "&ts=" + ts + "&sign=" + getToken(ts + "");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return params;
	}

	public static String getToken(String ts)
			throws UnsupportedEncodingException, NoSuchAlgorithmException {

		String result = Encoder.md5(appID + ts + token + false);

		result = Encoder.urlEncode(result);

		return result;
	}

	/**
	 * 获取WeiTown的Token
	 * 
	 * @param context
	 *            上下文
	 * @param isCarryToken
	 *            是否需要携带token,true为携带，false为不携带
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String FetchToken(Context context, boolean isCarryToken)
			throws UnsupportedEncodingException {

		// String device = Constant.tokenID;
		String device = SharePreferenceHelper.getStringValue(context,
				SharePreferenceHelper.mDeviceID);
		String ver = VersionHelper.getVersionCode(context) + "";
		String platform = "hengdaandroid";
		String model = Build.MANUFACTURER;
		String sdkver = "Android" + android.os.Build.VERSION.RELEASE;
		String appid = "103";
		String ct = "c";
		String param = "";

		if (isCarryToken) {
			String token = SharePreferenceHelper.getToken(context);
			// 获取账户信息 主要为了拿到cid
			User account = SharePreferenceHelper.GetAccount(context);
			String cid = (account != null ? account.getUid() : "");
			// 当前系统时间戳
			String timestamp = DateUtils.getCurrentDate() + "";
			// (cid + token + timestamp)md5加密后的token
			String tokenUrl = md5(cid + token + timestamp);

			param = "?device=" + device + "&ver=" + ver + "&platform="
					+ platform + "&model=" + model + "&sdkver=" + sdkver
					+ "&appid=" + appid + "&ct=" + ct + "&cid=" + cid
					+ "&timestamp=" + timestamp + "&token=" + tokenUrl;

		} else {
			param = "?device=" + device + "&ver=" + ver + "&platform="
					+ platform + "&model=" + model + "&sdkver=" + sdkver
					+ "&appid=" + appid + "&ct=" + ct;
		}

		param = param.toString().replace(" ", "%20").replace("\"", "%22")
				.replace("{", "%7b").replace("}", "%7d");

		return param;
	}

	/**
	 * 对字符串MD5加密
	 * 
	 * @param string
	 * @return
	 */
	public static String md5(String string) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(
					string.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}

	/**
	 * 获取KaKaTool请求token
	 * 
	 * @param context
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String FetchKaKaToolToken(Context context)
			throws UnsupportedEncodingException {

		// String device = Constant.tokenID;
		String device = SharePreferenceHelper.getStringValue(context,
				SharePreferenceHelper.getStringValue(context,
						SharePreferenceHelper.mDeviceID));

		String ver = VersionHelper.getVersionCode(context) + "";
		String platform = "hengdaandroid";
		String model = Build.MANUFACTURER;
		String sdkver = "Android" + android.os.Build.VERSION.RELEASE;
		String token = SharePreferenceHelper.getToken(context);
		String ct = "c";

		String tokenUrl = token;

		try {
			tokenUrl = URLEncoder.encode(token, "utf-8");
		} catch (Exception e) {

		}

		String param = "?device=" + device + "&ver=" + ver + "&platform="
				+ platform + "&model=" + model + "&sdkver=" + sdkver
				+ "&token=" + tokenUrl + "&ct=" + ct;

		param = param.toString().replace(" ", "%20").replace("\"", "%22")
				.replace("{", "%7b").replace("}", "%7d");
		return param;
	}

	/**
	 * 获取首页列表的Token
	 * 
	 * @param context
	 *            上下文
	 * @param isCarryToken
	 *            是否需要携带token,true为携带，false为不携带
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String FetchColourTokenDelHomeList(Context context,
			String source_id, boolean isCarryNameAndPassword)
			throws UnsupportedEncodingException {

		// Date d = new Date();
		// SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		// String timestamp = formatter.format(d);
		long ts = DateUtils.getCurrentDate();

		String params = "";
		try {
			if (isCarryNameAndPassword) {
				SharedPreferences sp = context.getSharedPreferences("a.xml", 0);
				String accountId = sp.getString("accountId", "");

				params = "?usernames=" + accountId + "&source_id=" + source_id
						+ "&sign=" + getToken(ts + "") + "&ts=" + ts
						+ "&appID=" + appID;
			} else {
				params = "?appID=" + appID + "&ts=" + ts + "&sign="
						+ getToken(ts + "");
			}

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return params;
	}

	/**
	 * 消息推送注册registrationId获取的Token
	 * 
	 * @param context
	 *            上下文
	 * @param isCarryToken
	 *            是否需要携带token,true为携带，false为不携带
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static RequestParams FetchColourTokenDelregistrationId(
			Context context, boolean isCarryNameAndPassword, String lat,
			String lng, String registrationId)
			throws UnsupportedEncodingException {

		// Date d = new Date();
		// SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		// String timestamp = formatter.format(d);
		long ts = DateUtils.getCurrentDate();
		RequestParams params = new RequestParams();
		try {
			if (isCarryNameAndPassword) {
				SharedPreferences sp = context.getSharedPreferences("a.xml",
						0);
				String username = sp.getString("id", "");
				params.put("registrationID", registrationId);
				params.put("lat", lat);
				params.put("lng", lng);
				params.put("uid", username);
				params.put("ts", ts + "");
				params.put("sign", getToken(ts + ""));
				params.put("appID", appID);
			} else {

			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return params;
	}

	// 修改个人信息
	public static RequestParams fetchColourTokenChangePersoninfo(
			Context context, boolean isCarryNameAndPassword,
			String ChangePhoneJson) throws UnsupportedEncodingException {
		long ts = DateUtils.getCurrentDate();
		RequestParams params = new RequestParams();
		try {
			if (isCarryNameAndPassword) {
				params.put("json", ChangePhoneJson);
				params.put("ts", ts + "");
				params.put("sign", getToken(ts + ""));
				params.put("appID", appID);
			} else {

			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return params;
	}

	// 群组加人
	public static RequestParams FetchColourToken7(Context context,
			boolean isCarryNameAndPassword, String groupid, String usernames)
			throws UnsupportedEncodingException {
		RequestParams param = new RequestParams();
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			if (isCarryNameAndPassword) {
				param.put("sign", sign);
				param.put("ts", ts + "");
				param.put("appID", appID);
				param.put("id", groupid);
				param.put("usernames", usernames);

			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return param;
	}

	public static RequestParams FetchColourToken_changegroupname(
			Context context, boolean isCarryNameAndPassword, String id,
			String groupname, String description, String maxusers)
			throws UnsupportedEncodingException {
		RequestParams param = new RequestParams();
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			if (isCarryNameAndPassword) {
				param.put("sign", sign);
				param.put("ts", ts + "");
				param.put("appID", appID);
				param.put("id", id);
				param.put("groupname", groupname);
				param.put("description", description);
				param.put("maxusers", maxusers);
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return param;
	}

}
